(function(){
	
	var isSetTip = typeof window.setPlaceHolder =="function";
	
	//赋值方法
	function setValue(target, value){
		if(target && typeof target.val == "function"){
			target.val(value);
		}
	}
	
	//给地址输入框赋值
	function setAddressValue(target, value){
		setValue(target, value);
		if(isSetTip && target.attr("placeholder")){
			target.trigger("_reset");
		}
	}
	
	var MapConfig = window.MapConfig ||{};
	window.MapConfig = MapConfig;
	
	function Map(config){
		this.init(config);
	}
	
	Map.prototype = {
		init : function(config){
			var defaults = {
				mapDivId : null ,// 可视区域id
				lngEl : null,// 经度原素
				latEl : null,// 纬度原素
				addressEl : null , // 地址描述原素
				lng : null,
				lat : null,
				defaultLng : MapConfig.defaultLng,
				defaultLat : MapConfig.defaultLat,
				markerChange : null
			};
			this.config = $.extend(defaults , config);
			this.curentPosition = new BMap.Point(this.config.lng ? this.config.lng : this.config.defaultLng,this.config.lat ? this.config.lat : this.config.defaultLat);
			this.initMap();
			this.initMyGeo();
			this.initMarker();
			this.bindEvent();
			if(!this.config.lng && !this.config.lat){
				this.focusToLocal();
			}
		} ,
		initMap : function(){
			this.map = new BMap.Map(this.config.mapDivId);
			this.map.enableScrollWheelZoom();
			this.map.enableDragging();
			this.map.enableContinuousZoom();
			this.map.addControl(new BMap.NavigationControl());
			this.map.addControl(new BMap.ScaleControl());
			this.map.addControl(new BMap.OverviewMapControl());
			
			this.map.setCenter(this.curentPosition);
			this.map.centerAndZoom(this.curentPosition, 15);
			this.map.panTo(this.curentPosition);
		},
		initMarker : function(){
			this.marker = new BMap.Marker(this.curentPosition);
			this.map.addOverlay(this.marker); // 将标注添加到地图中
			this.marker.enableDragging();
		},
		initMyGeo : function(){
			var _this = this;
			this.myGeo = new BMap.Geocoder();
		} , 
		bindEvent : function(){
			var _this = this;
			this.marker.addEventListener("dragend", function(e) {
				setValue(_this.config.lngEl, e.point.lng);
				setValue(_this.config.latEl, e.point.lat);
				_this.myGeo.getLocation(new BMap.Point(e.point.lng, e.point.lat),function(result) {
					if (result) {
						setAddressValue(_this.config.addressEl, result.address);
						
						var position = new BMap.Point(e.point.lng, e.point.lat);
						_this.marker.setPosition(position);
						if(_this.config.markerChange){
							var response = {
								province:result.addressComponents.province,
								city:result.addressComponents.city,
								district:result.addressComponents.district,
								street:result.addressComponents.street,
								address:result.address,
								longitude:e.point.lng,
								latitude: e.point.lat
							};
							_this.config.markerChange(response);
						}
						_this.map.panTo(position);
					}
				});
			});
			
			this.map.addEventListener("dragend",function showInfo() {
				var cp = _this.map.getCenter();
				_this.myGeo.getLocation(new BMap.Point(cp.lng, cp.lat),function(result) {
					if (result) {
						setAddressValue(_this.config.addressEl, result.address);
						setValue(_this.config.lngEl, cp.lng);
						setValue(_this.config.latEl, cp.lat);
						
						var position = new BMap.Point(cp.lng, cp.lat);
						_this.marker.setPosition(position);
						if(_this.config.markerChange){
							var response = {
								province:result.addressComponents.province,
								city:result.addressComponents.city,
								district:result.addressComponents.district,
								street:result.addressComponents.street,
								address:result.address,
								longitude:cp.lng,
								latitude: cp.lat
							};
							
							_this.config.markerChange(response);
						}
						_this.map.panTo(position);
					}
				});
			});
			// 
			this.map.addEventListener("dragging", function showInfo() {
				var cp = _this.map.getCenter();
				var position = new BMap.Point(cp.lng, cp.lat);
				_this.marker.setPosition(position);
				_this.map.centerAndZoom(position, _this.map.getZoom());
				_this.map.panTo(position);
			});
		},
		focusToAddress : function(address){
			var _this = this;
			// 将结果显示在地图上，并调整地图视野
			var options = {
			      onSearchComplete: function(results){
			          if (local.getStatus() == BMAP_STATUS_SUCCESS){
			        	  var pois = results.getCurrentNumPois();
			        	  if(pois > 0){
			        		  	var point = results.getPoi(0).point;
								_this.marker.setPosition(new BMap.Point(point.lng, point.lat));
								if(_this.config.markerChange){
									var response = {
										province:results.province,
										city:results.city,
										district:results.district,
										street:results.street,
										address:address,
										longitude:point.lng,
										latitude: point.lat
									};
									
									_this.config.markerChange(response);
								}
								setValue(_this.config.lngEl ,point.lng);
								setValue(_this.config.latEl, point.lat);
								
								_this.map.centerAndZoom(_this.marker.getPosition(), _this.map.getZoom());
								_this.map.panTo(new BMap.Point(_this.marker.getPosition().lng, _this.marker.getPosition().lat));
			        	  }
			          }
			      }
			 };   
			var local = new BMap.LocalSearch(_this.map, options);
			local.search(address);
		},
		focusToLocal : function(){
			var _this = this;
			var myCity = new BMap.LocalCity();
			myCity.get(function(result){
				setAddressValue(_this.config.addressEl, result.name);
				_this.map.setZoom(15);
				_this.focusToAddress(result.name);
			});
		}
	}
	
	
	
	var baiduMap = window.baiduMap = {
		init : function(config){
			return new Map(config);
		}
	};

	



	if(window.jQuery || window.Zepto){
		
		
		(function($) {
			'use strict';
			/**
			 * 百度地图
			 * e.g:
			 *	$("#navigate_map").baiduMap({
			 *		searchBtn:$(".mapSearch"),
			 *		longitudeTarget:$("#longitude"),
			 *		latitudeTarget:$("#latitude"),
			 *		addressTarget:$("#address")
			 *	});
			 * @author rubekid
			 */
			$.fn.baiduMap = function(options) {
				var target = this.eq(0);
				var self = target.get(0);
				var settings = $.extend({}, options);
				if(self._initMap){
					return false;
				}
				self._initMap = true;

				if(typeof self.id ==  "undefined"){
					self.id = "mapDivId_" + (new Date()).getTime();
				}
				
				var config = {mapDivId:self.id , lngEl : settings.longitudeTarget , latEl : settings.latitudeTarget , addressEl : settings.addressTarget};
				var navigate = settings.navigate;
				if(navigate){
					var position = navigate.split("," , 3);
					config.lng = position[0];
					config.lat = position[1];
					config.address = position[2];
					
					setValue(config.lngEl, position[0]);
					setValue(config.latEl, position[1]);
					setAddressValue(config.addressEl, position[2]);
					
				} else {
					config.lng = null;
					config.lat = null;
					config.address = null;
				}
				// 位置修改触发
				config.markerChange = function(response){
					navigate = response.longitude + "," + response.latitude + "," + response.address;
					setValue(config.lngEl, response.longitude);
					setValue(config.latEl, response.latitude);
					if(typeof settings.markerChange == "function"){
						settings.markerChange(response);
					}
				};
				var map = baiduMap.init(config);
				
				if(config.addressEl){
					//搜索按钮事件
					settings.searchBtn.bind("click",function(){
						map.focusToAddress( config.addressEl.val());
					});
					//输入回车事件
					config.addressEl.keypress(function(e) {
						if (e.keyCode == 13) {
							map.focusToAddress(config.addressEl.val());
						}
					});
					if(isSetTip && config.addressEl.attr("placeholder")){
						setPlaceHolder({target:config.addressEl});
					}
				}
				if(!config.lng && !config.lat){
					map.focusToLocal();
				}
				return target;
			};
		})(window.jQuery || window.Zepto);
	}

})();
